﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LPY.LeHealth.Service;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core;
using Aliyun.Acs.Sms.Model.V20160927;
using Aliyun.Acs.Core.Exceptions;
using System.Configuration;
using LPY.LeHealth.DTO;
using LPY.LeHealth.WebSite.Common;
using LPY.LeHealth.Model;
using LPY.LeHealth.DAL;

namespace LPY.LeHealth.WebSite.Controllers
{


    public class ApiController : Controller
    {
        ClassifyTypeDAL dal = new ClassifyTypeDAL();
        //接口示例
        //[HttpPost]
        //public ActionResult Login(string name, string pwd)
        //{
              //统一消息格式
        //    Common.JsonMessage jm = new Common.JsonMessage();

        //    //逻辑处理
        //    if (name == "admin" && pwd == "admin")
        //    {
        //        jm.Code = 1;
        //        jm.Msg = "验证成功";
        //        //jm.Data  //需要返回数据时赋值
        //    }
        //    else
        //    {
        //        jm.Code = 0;
        //        jm.Msg = "验证失败";
        //    }

        //    return Json(jm);
        //  }

        private UserService userService;
        private PhysicalService physicalService;
        private CartService cartService;
        private OrderService orderService;
        private ComboService comboService;
        private CrowdService crowdService;
        public ApiController()
        {
            userService = new UserService();
            physicalService = new Service.PhysicalService();
            cartService = new Service.CartService();
            orderService = new Service.OrderService();
            comboService = new Service.ComboService();
            crowdService = new CrowdService();
        }

        #region V2.0

        #region 模块1：体检

        [HttpPost]
        public ActionResult GetComboList(int comboTypeId, int pageIndex, int pageSize)
        {
            Common.PagerMessage pm = new PagerMessage();

            long totalSize=0;

            var data = physicalService.GetComboList(comboTypeId,pageIndex, pageSize, out totalSize);

            if(null!=data && data.Count>0)
            {
                pm.Code = 1;
                pm.Msg = "获取数据成功";
                pm.pageIndex = pageIndex;
                pm.pageSize = pageSize;
                pm.totalSize = totalSize;
                pm.Data = data;
            }
            else
            {
                pm.Code = 0;
                pm.Msg = "无数据";
            }

            return Json(pm);
        }

        #endregion

        #region 模块2：用户

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phone">手机号码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SendSms(string phone)
        {
            //生成短信验证码
            var code = Common.SecurityHelper.CreateCode(6);
            Session[phone] = code;
            Session.Timeout = 10;

            var msg=SmsHelper.SendSecurityCode(phone, code);

            return Json(msg);
        }

        /// <summary>
        /// 手机号和密码登录
        /// </summary>
        /// <param name="mob"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string mob, string pwd)
        {
            Common.JsonMessage msg = new Common.JsonMessage();
            if (!string.IsNullOrEmpty(mob) && !string.IsNullOrEmpty(pwd))
            {
                var usr = userService.GetByPhoneNumber(mob);
                if (null != usr)
                {
                    if(usr.Password!=pwd)
                    {
                        msg.Code = 2;
                        msg.Msg = "密码不正确";
                    }
                    else
                    {
                        msg.Code = 1;
                        msg.Msg = "登录成功";
                        Session["mob"] = mob;
                        Session["id"] = usr.Id;
                        var token = Common.TokenHelper.CreateToken(usr.Id);
                        msg.Data = token;
                    }
                }
                else
                {
                    msg.Code = 0;
                    msg.Msg = "用户不存在，请先注册";
                }
            }
            else
            {
                msg.Code = 0;
                msg.Msg = "用户名或密码不能为空";
            }
            return Json(msg);
        }

        /// <summary>
        /// 手机号和验证码登录
        /// </summary>
        /// <param name="mob"></param>
        /// <param name="yzm"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PhoneLogin(string mob, string yzm)
        {
            Common.JsonMessage msg = new Common.JsonMessage();
            if (!string.IsNullOrEmpty(mob) && !string.IsNullOrEmpty(yzm))
            {
                var code = Session[mob];
                if (null != code && code.ToString() == yzm)
                {
                    msg.Code = 1;
                    msg.Msg = "验证成功";

                    //先判断数据库是否存在该手机号
                    var user = userService.GetByPhoneNumber(mob);
                    if (null == user)
                    {
                        UserDTO dto = new UserDTO();
                        dto.PhoneNumber = mob;
                        dto.Password = Common.SecurityHelper.CreateCode(6);
                        dto.Name = mob;
                        dto.PrivileteId = 0;
                        dto.RoleId = 0;
                        var uid = userService.Add(dto);

                        //返回Token到客户端
                        msg.Data = Common.TokenHelper.CreateToken(uid);
                        //发送账户短信
                        SmsHelper.SendRegisterInfo(mob, dto.Password);
                    }
                    else
                    {
                        //已经存在则直接返回Token
                        msg.Data = Common.TokenHelper.CreateToken(user.Id);
                    }
                }
                else
                {
                    msg.Code = 0;
                    msg.Msg = "验证码无效";
                }
            }
            else
            {
                msg.Code = 0;
                msg.Msg = "手机或验证码不能为空";
            }
            return Json(msg);
        }

        /// <summary>
        /// 判断是否登录
        /// </summary>
        /// <returns></returns>
        [Token]
        [HttpPost]
        public ActionResult IsLogin()
        {
            Common.JsonMessage jm = new JsonMessage();
            jm.Code = 0;
            jm.Msg = "获取用户信息失败";

            var tokens = Request.Headers.GetValues("token");

            if (tokens.Length > 0 && tokens[0] != "null")
            {
                var secretKey = ConfigurationManager.AppSettings["jwt_secret_key"];
                var jsonPayload = JWT.JsonWebToken.DecodeToObject<Dictionary<string, object>>(tokens[0], secretKey);

                var uid = (int)jsonPayload["id"];
                var usr = userService.GetById(uid);
                if (null != usr)
                {
                    usr.Password = "";
                    jm.Code = 1;
                    jm.Msg = "获取用户信息成功";
                    jm.Data = usr;
                    Session["useid"] = uid;
                }
            }
            return Json(jm);
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="u"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Register(string mob,string pwd,string yzm)
        {
            Common.JsonMessage msg = new Common.JsonMessage();
            if (!string.IsNullOrEmpty(mob) && !string.IsNullOrEmpty(pwd) && !string.IsNullOrEmpty(yzm))
            {
                var code = Session[mob];
                if (null != code && code.ToString() == yzm)
                {
                    //先判断数据库是否存在该手机号
                    var user = userService.GetByPhoneNumber(mob);
                    if (null == user)
                    {
                        msg.Code = 1;
                        msg.Msg = "注册成功";
                        UserDTO dto = new UserDTO();
                        dto.PhoneNumber = mob;
                        dto.Password = pwd;
                        dto.Name = mob;
                        dto.PrivileteId = 0;
                        dto.RoleId = 0;
                        var uid = userService.Add(dto);

                        //返回Token到客户端
                        //msg.Data = Common.TokenHelper.CreateToken(uid);

                        //发送账户短信
                        SmsHelper.SendRegisterInfo(mob, dto.Password);
                    }
                    else
                    {
                        msg.Code = 2;
                        msg.Msg = "该手机号已经注册，可使用短信验证登录";
                    }
                }
                else
                {
                    msg.Code = 3;
                    msg.Msg = "验证码无效";
                }
            }
            else
            {
                msg.Code = 0;
                msg.Msg = "手机或验证码不能为空";
            }
            return Json(msg);
        }

        #endregion


        #endregion



        /// <summary>
        /// 修改之前获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetId()
        {
            int id = Convert.ToInt32(Session["useid"]);
            UserDTO list = userService.GetById(id);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 修改昵称
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult UpdateName(int id, string name)
        {
            id = Convert.ToInt32(Session["useid"]);
            return Json(userService.UpdateName(id, name), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 修改姓名
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult UpdateTrueName(int id, string name)
        {
            id = Convert.ToInt32(Session["useid"]);
            return Json(userService.UpdateTrueName(id, name), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public int Updapwd(string Password)
        {
            int id = Convert.ToInt32(Session["useid"]);
            int result=Convert.ToInt32(userService.Updapwd(id, Password));
            return result;
        }
        
        /// <summary>
        /// 新增联系人
        /// </summary>
        /// <returns></returns>
        public JsonResult show()
        {
            int id = Convert.ToInt32(Session["useid"]);
            makeDAL dal = new makeDAL();
            List<subscrib> list = dal.show(id);
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 预约人信息
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public int yuyue(subscrib s)
        {
            List<subscrib> list = new List<subscrib>();
            
            int id = Convert.ToInt32(Session["useid"]);
            
            s.uid = id;
            List<OrderDetail> orderDetail_list = new List<OrderDetail>();
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.ComboId = Convert.ToInt32(s.Cid);
            orderDetail.UserId = s.uid;
            orderDetail_list.Add(orderDetail);
            makeDAL dal = new makeDAL();
            if (dal.Addmake(s,id) > 0)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }


        /// <summary>
        /// 根据体检类型，获取该类型的套餐列表
        /// </summary>
        /// <param name="tj_type"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult tj_list_show(string tj_type)
        {

            int type;
            var d1 = new List<Combo>();
            try
            {
                type = Convert.ToInt32(tj_type);
            }
            catch
            {
                type = 0;
            }
            long xx;
            if (0 == type)
            {
                d1 = physicalService.GetPhysicalCombo(1, 10, out xx);
            }
            else
            {
                d1 = comboService.GetComboByType(Convert.ToInt32(tj_type));
            }


            return Json(d1);

        }

        /// <summary>
        /// 根据id，获取该套餐详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult tj_list_details_show(int id)
        {
            JsonMessage jm = new JsonMessage();
            //int theid;
            //try
            //{
            //     theid = Convert.ToInt32(id);
            //}
            //catch
            //{
            //    theid = 0;
            //    jm.Code = 0;
            //    jm.Msg = "参数出错";
            //}

            var combo = physicalService.GetCombo(id);
            if(null!=combo)
            {
                jm.Code = 1;
                jm.Msg = "获取数据成功";
                jm.Data = combo;
            }
            else
            {
                jm.Code = 0;
                jm.Msg = "获取数据失败";
            }
            
            return Json(jm);
        }

        /// <summary>
        /// 忘记密码下一步功能
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="authCode"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult do_forget_next(string mobile,string authCode)
        {
            Common.JsonMessage jm=new Common.JsonMessage();
            if(null==mobile||null==authCode)
            {
                jm.Code = 0;
                jm.Msg = "手机号与验证码不能为空";
                
            }

            if(null==Session["authcode"])
            {
                jm.Code = 0;
                jm.Msg = "请再次获取验证码";
                return Json(jm);
            }


            if(Session["authcode"].ToString()==authCode)
            {
                jm.Code = 1;
                jm.Msg = "验证码验证成功";
                Session["mobile"] = mobile;
            }

            return Json(jm);
        }



        /// <summary>
        /// 体检套餐预定功能
        /// </summary>
        /// <returns></returns>
        public ActionResult add_ajax_orders(int Cid, string Phyname, string PhyDate, string PhyPhone, string Phycard, int Physex, string marital, decimal? Phyprice, string makePhone, string remark, string tjrsfz)
        {
            //根据套餐Id获取套餐信息（价格）
            var combo = physicalService.GetCombo(Cid);

            //创建订单

            //创建订单详情

            var tjr_name =Phyname;// Phyname; //Request["tjr_name"];//体检人名称
            var tj_time =PhyDate;// Request["tj_time"];//预约时间
            var tjr_sj =PhyPhone; //Request["tjr_sj"];//手机号码
            var tjr_sfz =Phycard; //Request["tjr_sfz"];
            var tjr_xb =Physex; //Request["tjr_xb"];//性别 1男，0女
            var tjr_hf =marital; //Request["tjr_hf"];//婚否 0未婚，1已婚
            var money = combo.Price;// Phyprice; //Request["money"];//订单金额
            var tj_list_id = Cid; //Request["tj_list_id"];//套餐id
            var uid=Convert.ToInt32(Session["useid"]);
            //var tjr_sfz = tjrsfz;
            if(uid>0)
            {
                List<OrderDetail> orderDetail_list = new List<OrderDetail>();
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.ComboId = Convert.ToInt32(tj_list_id);
                orderDetail.UserId = uid;
                orderDetail_list.Add(orderDetail);

                Order order = new Order();
                order.BookerName = tjr_name;
                order.BookerPhone = tjr_sj;
                order.BookerSex = tjr_xb;
                order.CreateDate = tj_time;
                order.SumPrice = money;
                order.PreferentialPrice = money;
                order.UserId = uid;
                order.State = 0;
                order.Details = orderDetail_list;
                order.TpeopleAdd = tjr_sfz;//获取体检人身份证
                //订单交易号
                order.PayCode = WxPayAPI.WxPayApi.GenerateOutTradeNo();
                var orderId = orderService.CreateOrder(order);

                if (orderId > 0)
                {   string ordercode=orderService.OrderString();//获取最新的订单号
                    orderService.InsertOrderdetails(ordercode, uid, Convert.ToInt32(tj_list_id), 0);//写入订单明细表
                    //跳转到支付页面
                    return RedirectToAction("PrePay", "WeChatPay", new { oid = orderId });
                    //return 1;
                }
                else
                {
                    //return 0;
                    return Content("创建订单失败，请联系管理员！");
                }
            }
            else
            {
                return Content("未识别的用户，如果您是注册用户请先登录！");
            }
        }


        /// <summary>
        /// 获取全部套餐类型
        /// </summary>
        /// <returns></returns>
        public ActionResult getComboType()
        {
            var d1=comboService.getComboType();
            return Json(d1);
        }


        /// <summary>
        /// 判定是否已经登录，如果已经登录，返回用户信息
        /// </summary>
        /// <returns></returns>
        public JsonResult if_register()
        {
            Session["user_id"] = 1;
            Session["user_info"] = "18811742118";
            JsonMessage jm = new JsonMessage();
            if(null==Session["user_info"])
            {
                jm.Code = 0;
                jm.Msg = "尚未登录";
            }else
            {
                jm.Code = 1;
                jm.Msg = "已经登录";
                var name=Session["user_info"].ToString();
                jm.Data = name;
            }

           return Json(jm);
        }



        /// <summary>
        /// 获取订单功能（根据用户id，获取该用户订单信息）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult my_order()
        {
            JsonMessage jm = new JsonMessage();
            if (null == Session["id"])
            {
                jm.Code = 0;
                jm.Msg = "session值为空，请解决该错误";
                return Json(jm);
            }

            var id = Convert.ToInt32(Session["id"]);

            jm.Code = 1;
            jm.Msg = "获取该用户的订单信息";
            jm.Data = orderService.GetOrderList(id,-1);
            
           return Json(jm);
        }
        /// <summary>
        /// 获取订单数
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderCount()
        {
            var id = Convert.ToInt32(Session["useid"]);
            return Json(orderService.GetOrderCount(id));
        }


        /// <summary>
        /// 订单详情页（根据用户id与该用户的订单id，返回该订单详细信息）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public JsonResult my_order_details(string Id)
        {
            JsonMessage jm = new JsonMessage();
            if (null == Session["id"])
            {
                jm.Code = 0;
                jm.Msg = "session值为空，请解决该错误";
                return Json(jm);
            }

            var orderId=0;
            try
            {
                 orderId=Convert.ToInt32(Id);
            }
            catch
            {
                orderId=0;
            }

            var user_id = Convert.ToInt32(Session["id"]);
            var d1 = orderService.GetIndentList(user_id, orderId);

            jm.Code = 1;
            jm.Msg = "获取数据成功";
            jm.Data = d1.FirstOrDefault();

            return Json(jm);
        }


        /// <summary>
        /// 删除订单（根据订单id删除该订单）
        /// </summary>
        /// <returns></returns>
        public JsonResult del_order(string id)
        {
            JsonMessage jm = new JsonMessage();
            int order_id;
            try
            {
                order_id = Convert.ToInt32(id);
            }
            catch
            {
                jm.Code = 0;
                jm.Msg = "参数错误";
                return Json(jm);
            }

            var d1 = orderService.del_order(order_id);

            if(d1>0)
            {
                jm.Code = 1;
                jm.Msg = "删除了一个订单";
            }
            else
            {
                jm.Code = 0;
                jm.Msg = "未删除任何订单";
            }

            return Json(jm);
        }


        /// <summary>
        /// 测试方法功能
        /// </summary>
        public void test()
        {
            long y;
            var d1=physicalService.GetAllComboType();//所有体检类型
             var d2=physicalService.GetAllPhysicalItem();//所有体检项目
             var d3=physicalService.GetCombo(1);//根据id获取套餐信息
             var d5=physicalService.GetPhysicalCombo(1,10,out y);//获取套餐信息
             var d6 = physicalService.GetPhysicalComboDTO(1, 10, out y);
             var d7=physicalService.GetPhysicalItemById(1);
             var d8 = physicalService.GetPhysicalItemList(1, 10, out y);
             var d9=physicalService.GetPhysicalsByHospitalId(1);
             var d10 = physicalService.GetPhysicalSingle(1, 10, out y);
             var d11 = physicalService.GetPhysicalSingleDTO(1, 10, out y);
            var d12=physicalService.GetType();


        }
        /// <summary>
        /// 添加提交问题信息
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public int QueAdd(questions q)
        {

            q.Uid = Convert.ToInt32(Session["useid"]);
            q.Qdate =DateTime.Now.ToString();

            if(dal.QueAdd(q)>0)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }


        /// <summary>
        /// 获取适合人群名称
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCrowd()
        {
            var d = crowdService.GetCrowdList();
            return Json(d);
        }

        [HttpGet]
        public string SelectSession()
        {
            if(Session["mob"]==null)
            {
                return "19012345678";
            }

            return Session["mob"].ToString();
        }
    }
}